require(
    ['jquery', 'views/map', 'views/areas', 'views/select', 'views/search'],
    function ($, Map, Areas, Select) {
        $(function () {
            var map = new Map()
            map.Init()

            var areas = new Areas()
            areas.Init()
            window.areas = areas

            var selector = new Select()
            selector.Init()

            GetUserPosition()
            // 添加访问记录
            AddVisitRecord()
        })


        function GetUserPosition() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            }
            function showPosition(position) {
                console.log(position);
                var lat = Number(position.coords.latitude.toFixed(6)); //纬度 
                var lng = Number(position.coords.longitude.toFixed(6)); //经度 
                gcj = GPS.gcj_encrypt(lat, lng)
                console.log('纬度:' + lat + ',经度:' + lng);
                console.log(gcj)
                // window.map.setView(L.latLng(lat, lng), 11)
                window.map.setView(L.latLng(gcj.lat, gcj.lon), 11)
                // todo 定位到当前行政区划
                window.Regeo(lng, lat).done(function (resp) {
                    var region = resp.regeocode.addressComponent
                    var province = region.province.replace('省', '').replace('自治区', '')
                    var city = region.city.replace('市', '')

                    if (province) {
                        $('#provice').selectpicker('val', province)
                        $('#provice').change()
                    }
                    if (province && city) {
                        $('#city').selectpicker('val', city)
                        $('#city').change()
                    }

                }).fail(function (error) {
                    console.error(error)
                })


            }
            function showError(error) {
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        console.log("定位失败,用户拒绝请求地理定位");
                        break;
                    case error.POSITION_UNAVAILABLE:
                        console.log("定位失败,位置信息是不可用");
                        break;
                    case error.TIMEOUT:
                        console.log("定位失败,请求获取用户位置超时");
                        break;
                    case error.UNKNOWN_ERROR:
                        console.log("定位失败,定位系统失效");
                        break;
                }
            }


        }
        /**
         * 根据经纬度获取当前所在城市
         */
        window.Regeo = function (lng, lat) {
            var key = window.randomKey()
            var url = 'https://restapi.amap.com/v3/geocode/regeo?key=' + key + '&poitype=行政区划&radius=0&extensions=all&batch=false&roadlevel=1'

            url += '&location=' + lng + ',' + lat
            return $.ajax({
                url: url,
                type: 'get'
            })
        }


        // 提供gps转gcj坐标的方法 
        window.GPS = {
            PI: 3.14159265358979324,
            x_pi: 3.14159265358979324 * 3000.0 / 180.0,
            delta: function (lat, lon) {
                // Krasovsky 1940
                //
                // a = 6378245.0, 1/f = 298.3
                // b = a * (1 - f)
                // ee = (a^2 - b^2) / a^2;
                var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
                var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
                var dLat = this.transformLat(lon - 105.0, lat - 35.0);
                var dLon = this.transformLon(lon - 105.0, lat - 35.0);
                var radLat = lat / 180.0 * this.PI;
                var magic = Math.sin(radLat);
                magic = 1 - ee * magic * magic;
                var sqrtMagic = Math.sqrt(magic);
                dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
                dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
                return { 'lat': dLat, 'lon': dLon };
            },

            //GPS---高德
            gcj_encrypt: function (wgsLat, wgsLon) {
                if (this.outOfChina(wgsLat, wgsLon))
                    return { 'lat': wgsLat, 'lon': wgsLon };

                var d = this.delta(wgsLat, wgsLon);
                return { 'lat': wgsLat + d.lat, 'lon': wgsLon + d.lon };
            },
            outOfChina: function (lat, lon) {
                if (lon < 72.004 || lon > 137.8347)
                    return true;
                if (lat < 0.8293 || lat > 55.8271)
                    return true;
                return false;
            },
            transformLat: function (x, y) {
                var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
                ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
                ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
                ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
                return ret;
            },
            transformLon: function (x, y) {
                var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
                ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
                ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
                ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
                return ret;
            }
        };

        // 判断是否为手机端
        window.isMobile = function () {
            var userAgentInfo = navigator.userAgent;
            var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
            var flag = false;
            for (var v = 0; v < Agents.length; v++) {
                if (userAgentInfo.indexOf(Agents[v]) > 0) {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
        
        function AddVisitRecord(){
            $.ajax({
                url:'http://i2b7602620.qicp.vip/emergency/countVisit',
                type:'get'
            })
        }

        // 高德地图key
        window.randomKey = function () {
            var mapkeys = ['d0e115a4da6f06ebddbb72fb7d9a58ad',
                '9454f2a509eb94d46787c9d78b270b3d',
                '12b8b8b8b01684775fec8de8886a551f',
                '034f60f9e2e0b77433ac87fa43a5225d']

            function random(min, max) {
                return Math.floor(Math.random() * (max - min)) + min;
            }


            // var nmb = Math.floor(Math.random() * 10) % (mapkeys.length)
            var nmb = random(0,mapkeys.length)
            return mapkeys[nmb]
        }
    })




